package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetMealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : [chenxys]
 * @version : [v1.0]
 * @Description : 报表操作
 * @createTime : [2022/6/1 09:32]
 */
@RestController
@RequestMapping(value = "/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetMealService setMealService;
    @Reference
    private ReportService reportService;

    /**
     * 会员折线图
     * @author chenxys
     * @return com.itheima.entity.Result
     */
    @RequestMapping(value = "/getMemberReport")
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    public Result getMemberReport(){
        Map<String,Object> map = new HashMap<String,Object>();
        List<String> month = new ArrayList<String>();

        //获取日历对象,默认时间为当前时间2022年6月1日
        Calendar calendar = Calendar.getInstance();
        //计算过去一年的12个月
        //              按照月份推       -12：向前推12；正值往后推
        calendar.add(Calendar.MONTH,-12);
        //2021年6月1日 ~ 2022年6月1日
        for (int i = 0;i < 12; i++){
            //2021年6月1日开始
            //当前日期[当前calendar所指定的时间]向后推一个月
            calendar.add(Calendar.MONTH,1);
            //获得日期[西方日期格式]
            Date date = calendar.getTime();
            //格式化日期为 -> 2021.06
            month.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        //将月存入map
        map.put("months",month);

        //获取当前日期之前的会员数量
        List<Integer> memberCount = memberService.findMemberCountByMonths(month);
        //将每月的会员数量存入map
        map.put("memberCount",memberCount);
        //返回数据
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    /**
     * 套餐预约占比饼形图
     * @author chenxys
     * @return com.itheima.entity.Result
     */
    @RequestMapping(value = "/getSetmealReport")
    @PreAuthorize("hasAuthority('REPORT_VIEW') and hasAuthority('SETMEAL_QUERY')")
    public Result getSetMealReport(){
        //构建数据模型
        Map<String,Object> data = new HashMap<String,Object>();
        //获取数据系列
        try {
            //存放查询出的数据
            List<Map<String,Object>> setmealCounts = setMealService.findSetmealCount();
            //存放套餐名称
            List<String> setmealNames = new ArrayList<String>();
            //存放需要的数据
            List<Map<String,Object>> setmealCount = new ArrayList<Map<String,Object>>();
            for (Map<String, Object> map : setmealCounts) {
                //获取值
                Long value = (Long)map.get("value");
                //如果当前值 > 0即预约该套餐的次数>0
                if (value.intValue() > 0){
                    //获取套餐名称
                    String name = (String) map.get("name");
                    //存入套餐名称
                    setmealNames.add(name);
                    //存入套餐名称和对应的值
                    setmealCount.add(map);
                }
            }
            //加入最终需要返回的map集合
            data.put("setmealNames",setmealNames);
            data.put("setmealCount",setmealCount);
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,data);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 返回运营相关数据
     * @author chenxys
     * @return com.itheima.entity.Result
     */
    @RequestMapping(value = "/getBusinessReportData")
    @PreAuthorize("hasAuthority('SETMEAL_QUERY') and hasAuthority('REPORT_VIEW')")
    public Result getBusinessReportData(){
        try {
            //存放最终返回的数据
            Map<String,Object> data = reportService.getBusinessReport();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
        } catch (Exception e) {
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出运营数据到Excel并下载
     * @author chenxys
     * @param request 请求头
     * @param response 响应头
     * @return com.itheima.entity.Result
     */
    @RequestMapping(value = "/exportBusinessReport")
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        //获取数据
        try {
            Map<String, Object> result = reportService.getBusinessReport();
            //获取日期
            String reportDate = (String) result.get("reportDate");
            //获取新增会员数
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            //获取总会员数
            Integer totalMember = (Integer) result.get("totalMember");
            //获取本周新增会员
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            //获取本月新增会员
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            //获取今日预约数
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            //获取今日就诊数
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            //获取本周预约数
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            //获取本周就诊数
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            //获取本月预约数
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            //获取本月就诊数
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            //获取热门套餐
            List<Map> hotSetmeal = (List<Map>)result.get("hotSetmeal");

            //获取template的目录
            String filePath = request.getSession().getServletContext().getRealPath("template") +
                    File.separator + "report_template.xlsx";

            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表 索引从0开始
            XSSFSheet sheet = excel.getSheetAt(0);
            //索引从0开始 竖着第3排[第三行]
            XSSFRow row = sheet.getRow(2);
            //写入日期  横着第6个单元格[第六个单元格]
            row.getCell(5).setCellValue(reportDate);

            //竖着第5排
            row = sheet.getRow(4);
            //第6个单元格 新增会员
            row.getCell(5).setCellValue(todayNewMember);
            //第8个单元格 总会员数
            row.getCell(7).setCellValue(totalMember);

            //竖着第6排
            row = sheet.getRow(5);
            //第6个单元格 本周新增会员数
            row.getCell(5).setCellValue(thisWeekNewMember);
            //第8个单元格 本月新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);

            //竖着第8排
            row = sheet.getRow(7);
            //第6个单元格 今日预约数
            row.getCell(5).setCellValue(todayOrderNumber);
            //第8个单元格 今日到诊数
            row.getCell(7).setCellValue(todayVisitsNumber);

            //竖着第9排
            row = sheet.getRow(8);
            //第6个单元格 本周预约数
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            //第8个单元格 本周到诊数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);

            //竖着第10排
            row = sheet.getRow(9);
            //第6个单元格 本月预约数
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            //第8个单元格 本月到诊数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);

            //竖着第13排
            int rowNum = 12;
            for (Map map : hotSetmeal) {
                //套餐名称
                String name = (String) map.get("name");
                //预约数量
                Long setmeal_count = (Long) map.get("setmeal_count");
                //占比
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                //每遍历一次就增加1行
                row = sheet.getRow(rowNum++);
                //第5个单元格 套餐名称
                row.getCell(4).setCellValue(name);
                //第6个单元格 预约数量
                row.getCell(5).setCellValue(setmeal_count);
                //第7个单元格 占比
                row.getCell(6).setCellValue(proportion.doubleValue());
                //第8个单元格 备注
            }

            //使用输出流进行表格下载
            ServletOutputStream out = response.getOutputStream();
            //设置响应类型             代表Excel
            response.setContentType("application/vnd.ms-excel");
            //指定以附件形式下载
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");
            //将内存中的excel写进模版
            excel.write(out);
            //刷新
            out.flush();
            //关闭资源
            out.close();
            excel.close();

            return null;
        } catch (Exception e) {
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出运营数据到PDF并下载
     * @author chenxys
     * @param request 请求头
     * @param response 响应头
     * @return com.itheima.entity.Result
     */
    @RequestMapping(value = "/exportBusinessReport4PDF")
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
        try {
            //获取数据
            Map<String, Object> report = reportService.getBusinessReport();
            //获取热门套餐
            List<Map> hotSetmeal = (List<Map>) report.get("hotSetmeal");

            //动态获取模版文件绝对磁盘路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") +
                    File.separator + "health_business3.jrxml";

            //存放编码后的模版文件路径
            String jasperPath = request.getSession().getServletContext().getRealPath("template") +
                    File.separator + "health_business3.jasper";

            //编译模版                                 模版路径   编译后存放路径
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

            //填充数据到模版 -- 使用JavaBean数据源方式填充              编译后模版    数据
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,report,
                    //JavaBean数据源
                    new JRBeanCollectionDataSource(hotSetmeal));

            //获取输出流
            ServletOutputStream out = response.getOutputStream();
            //设置响应头
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //输出文件                                填充好的模版文件,输出流
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
            out.flush();
            out.close();
            //返回
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
